// pages/communityList/communityList.js
var app = getApp();
Page({
  data: {
    banners: [
      
    ],
    communities: [],
    activeIndex: 0 // 默认展开第一条
  },
  onLoad() {
	  const self = this
	  self.setData({
		  banners:wx.getStorageSync('index_slides')
	  })
	  wx.getLocation({
	  	type: 'wgs84',
	  	success(res) {
	  		// 定位成功，获取最近的店，并提示是否切换
	  		//self.main_load(false);
	  		wx.setStorageSync('lng',res.longitude);
	  		wx.setStorageSync('lat',res.latitude);
	  		
	  	},
	  	fail(res) {
	  		console.log("fail");
	  		console.log(res);
	  	}
	  });
	  
	  app.util.getUserInfo(function (response) {
	  	console.log("==获取当前用户信息1==");
	  	console.log(response);
	  	self.setData({
	  		userInfo: response
	  	});
	  	console.log("==应用初始化：应用配置/应用中用户信息/当前城市信息==");
	  	
	  	setTimeout(function(){
	  		self.initData()
	  	},500)
	  });
	  // wx.checkSession({
	  // 	success() { 
	  // 		console.log('succ')
	  // 		self.initData()
	  // 	},
	  // 	fail() {
			// console.log('************************************')
	  // 	  wx.login({
	  // 		success: (loginRes) => {
	  // 		  if (loginRes.code) {
	  // 			// 发送登录code到服务器获取session_key
	  // 			app.util.getUserInfo(function (response) {
	  // 				self.initData()
	  // 			});
	  // 		  }
	  // 		}
	  // 	  })
	  // 	}
	  // });
  },
	initData:function(){
		let self = this
		app.mdInit(function (cfg,mine,area) {
			self.setData({
				cfg: cfg,
				mine:mine,
				area:area
			});
			let lng = wx.getStorageSync('lng')
			
			let lat = wx.getStorageSync('lat')
			if(lat && lng && 0){
				self.loadCommunityData(lng,lat);
			}else{
				wx.getLocation({
					type: 'wgs84',
					success(res) {
						// 定位成功，获取最近的店，并提示是否切换
						self.loadCommunityData(res.longitude,res.latitude);
					},
					fail(res) {
						wx.showToast({
						  title: '位置获取失败，请重新打开小程序',
						  icon: 'none'
						})
					}
				})
				}
		},{
				aid:self.data.aid,
				fuid:self.data.fuid,
				stid:self.data.fuid
		},true);
	},
    makePhoneCall:function(e){
        wx.makePhoneCall({
                phoneNumber: e.currentTarget.dataset.tel
        });
    },
  // 加载社区数据
  async loadCommunityData(lng,lat) {
    wx.showLoading({
      title: '加载中...',
    });
    const self = this;
	
	try {
		//console.log("self.data.like "+self.data.like);
		app.util.request({
			url: 'Community/index',
			data: {
				m: app.mdName,
				aid:self.data.area.id,
				lng:lng,
				lat:lat
			},
			complete(res) {
				wx.stopPullDownRefresh();
			},
			success(res) {
				var data = res.data.data;
				wx.hideLoading();
				self.setData({
					communities: data
				});
			}
		})
	} catch (error) {
      console.error('加载数据失败', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 切换社区展开状态
  toggleCommunity(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.activeIndex === index) {
      this.setData({ activeIndex: -1 }); // 点击已展开的则关闭
    } else {
      this.setData({ activeIndex: index });
    }
  },
	goCommunity(e){
		const id = e.currentTarget.dataset.id;
		wx.navigateTo({
			url:'../communitydoctor/detail?id='+id
		});
	},
  // 预约医生
  makeAppointment(e) {
    const doctor = e.currentTarget.dataset.doctor;
	console.log(doctor)
	wx.setStorageSync("selectDoctor",doctor)
	wx.navigateTo({
	  url: `/vp_pz/pages/communitydoctor/appintment`
	})
  },
// 导航到社区
  navigateToCommunity(e) {
    const { latitude, longitude, name } = e.currentTarget.dataset;
    
    wx.showActionSheet({
      itemList: ['腾讯地图', '高德地图'],
      success: (res) => {
        const mapApps = ['qqmap', 'amap'];
        const selectedApp = mapApps[res.tapIndex];
        
        wx.openLocation({
          latitude: parseFloat(latitude),
          longitude: parseFloat(longitude),
          name: name,
          address: name,
          scale: 18,
          success: () => {
            console.log('打开地图成功');
          },
          fail: (err) => {
            console.error('打开地图失败', err);
            wx.showToast({
              title: '打开地图失败',
              icon: 'none'
            });
          }
        });
      },
      fail: (err) => {
        console.error('用户取消选择', err);
      }
    });
  },
  // 轮播图点击事件
  onBannerTap(e) {
    const index = e.currentTarget.dataset.index;
    const banner = this.data.banners[index];
    if (banner.link) {
      wx.navigateTo({
        url: banner.link
      });
    }
  }
});